var id = T.p("id");
var workId = T.p("workId");

var dbKeys = T.getDictDynas("db_key");

var detailModes = T.getDictItems("detail_mode");

var subTypes = T.getDictItems("work_sub_type");

var cacheTypes = T.getDictItems("cache_type");

var initTableNameAuto = function (dbKey) {
    //取消autosuggest插件的上次轮询
    var intervalVaule = $("#tdTableName").attr("intervalVaule");
    if (intervalVaule) {
        clearInterval(intervalVaule);
    }

    $("#tdTableName").autosuggest({
        url: '../workDb/qryTablesByDbKey/' + dbKey,
        minLength: 1,
        maxNum: 10,
        align: 'center',
        method: 'get',
        highlight: true,
        immediate: true,
        queryParamName: 'qryName',
        onSelect: function (ele) {
            vm.workItem.tableFrom = ele.data('value');
        }
    });
};


var initTableToAuto = function (dbKey) {
    //取消autosuggest插件的上次轮询
    var intervalVaule = $("#tdTableTo").attr("intervalVaule");
    if (intervalVaule) {
        clearInterval(intervalVaule);
    }

    $("#tdTableTo").autosuggest({
        url: '../workDb/qryTablesByDbKey/' + dbKey,
        minLength: 1,
        maxNum: 10,
        align: 'center',
        method: 'get',
        highlight: true,
        immediate: true,
        queryParamName: 'qryName',
        onSelect: function (ele) {
            vm.workItem.tableTo = ele.data('value');
        }
    });
};


$(function () {
    $("#subJqGrid").jqGrid({
        url: '../workItemSub/subList',
        datatype: "json",
        postData: {itemId: id},
        colModel: [
            {label: 'id', name: 'id', width: 50, key: true, hidden: true},
            {label: '名称', name: 'subName', width: 200, sortable: false},
            {label: '类型', name: 'subType', width: 100, sortable: false},
            {label: 'dbKeyFrom', name: 'dbKeyFrom', hidden: true, sortable: false},
            {label: 'subSql', name: 'subSql', hidden: true, sortable: false},
            {label: 'cacheName', name: 'cacheName', hidden: true, sortable: false},
            {label: 'cacheKeyField', name: 'cacheKeyField', hidden: true, sortable: false},
            {label: 'cacheGetFields', name: 'cacheGetFields', hidden: true, sortable: false},
            {label: '排序号', name: 'orderNum', width: 100, sortable: false},
            {
                label: '操作',
                name: 'actions',
                sortable: false,
                width: 100,
                formatter: function (value, options, row, act) {
                    var opts = [];
                    opts.push('<a href="javascript:" class="btnList" title="编辑" onclick="vm.updateRow(' + options.rowId + ')" ><i class="fa fa-pencil"></i></a>&nbsp;');
                    opts.push('<a href="javascript:" class="btnList" title="删除子模块" data-confirm="确认要删除该子模块吗？" data-click="vm.deleteSubRow(' + options.rowId + ')"><i class="fa fa-trash-o"></i></a>&nbsp;');
                    opts.push('<a href="javascript:" class="btnList" title="添加子模块"  onclick="vm.createSub()"><i class="fa fa-plus"></i></a>');
                    return opts.join('');
                }
            }
        ],
        viewrecords: true,
        height: 'auto',
        rowNum: 9999,
        rownumbers: true,
        rownumWidth: 25,
        // toolbar: [true, "top"],
        autowidth: true,
        multiselect: false,
        jsonReader: {
            root: "page.data",
            page: "page.pageNo",
            total: "page.pageCount",
            records: "page.count"
        },
        gridComplete: function () {
            //隐藏grid底部滚动条
            $("#subJqGrid").closest(".ui-jqgrid-bdiv").css({"overflow-x": "hidden"});
            btnMoreEventBind("subJqGrid");
        }
    });

    $("#jqgh_subJqGrid_actions").append('<div class="pull-right" style="margin-right:10px;margin-top:2px"><a href="javascript:" class="btnList" title="添加子模块"  onclick="vm.createSub()"><i class="fa fa-plus"></i></a></div>');
});

var vm = new Vue({
    el: '#rrapp',
    data: {
        title: "新增",
        workItem: {
            workId: workId,
            chunk: 10000,
            execNum: 0,
            tableFrom: '',
            dbKeyFrom: dbKeys[0].dictCode,
            detailMode: detailModes[0].dictCode,
            dbKeyTo: dbKeys[0].dictCode,
            cacheType: cacheTypes[0].dictCode,
            readerType: 0,
            beanName: "",
            status: 1,
            expireTime: 24 * 60 * 60,
            processClassType: "springBean"
        },
        workItemSub: {},
        beans: "",
        processBeans: "",
        methods: "",
        dbKeys: dbKeys,
        detailModes: detailModes,
        selectEditor: null,
        subSqlEditor: null,
        insertEditor: null,
        deleteEditor: null,
        whereEditor: null,
        tdAutoSuggest: null,
        tableData: [],
        dialogFormVisibleForUpdate: false,
        dialogFormVisibleForAdd: false,
        editLoading: false,
        table_index: 999
    },
    mounted: function () {
        $('#rootwizard').bootstrapWizard({
            'tabClass': 'nav nav-pills',
            //此处解决多个codeMirror互相影响BUG需要异步刷新
            'onTabChange': function (tab, navigation, index) {
                setTimeout(function () {
                    vm.selectEditor.refresh();
                    vm.insertEditor.refresh();
                    vm.deleteEditor.refresh();
                    //vm.whereEditor.refresh();
                }, 50)
            }, onTabShow: function (tab, navigation, index) {
                var $total = navigation.find('li').length;
                var $current = index + 1;
                var $percent = ($current / $total) * 100;
                $('#rootwizard .progress-bar').css({width: $percent + '%'});
            }
        });
        this.selectEditor = CodeMirror.fromTextArea(document.getElementById('ta-select'), {
            mode: 'text/x-mysql',
            theme: 'rubyblue',
            // indentWithTabs: true,
            // smartIndent: true,
            lineNumbers: true,
            // styleActiveLine: true,
            // matchBrackets: true,
            autofocus: true
        });
        this.selectEditor.on('change', function () {
            vm.workItem.selectSql = vm.selectEditor.getValue();
        });
        this.insertEditor = CodeMirror.fromTextArea(document.getElementById('ta-insert'), {
            mode: 'text/x-mysql',
            theme: 'rubyblue',
            indentWithTabs: true,
            smartIndent: true,
            lineNumbers: true,
            styleActiveLine: true,
            matchBrackets: true,
            autofocus: true,
            extraKeys: {
                "F11": function (cm) {
                    cm.setOption("fullScreen", !cm.getOption("fullScreen"));
                },
                "Esc": function (cm) {
                    if (cm.getOption("fullScreen")) {
                        cm.setOption("fullScreen", false);
                    }
                },
                "Tab": "autocomplete"
            }
        });
        this.insertEditor.on('change', function () {
            vm.workItem.insertSql = vm.insertEditor.getValue();
        });
        this.deleteEditor = CodeMirror.fromTextArea(document.getElementById('ta-delete'), {
            mode: 'text/x-mysql',
            theme: 'rubyblue',
            indentWithTabs: true,
            smartIndent: true,
            lineNumbers: true,
            styleActiveLine: true,
            matchBrackets: true,
            autofocus: true,
            extraKeys: {
                "F11": function (cm) {
                    cm.setOption("fullScreen", !cm.getOption("fullScreen"));
                },
                "Esc": function (cm) {
                    if (cm.getOption("fullScreen")) {
                        cm.setOption("fullScreen", false);
                    }
                },
                "Tab": "autocomplete"
            }
        });
        this.deleteEditor.setSize('auto', '100px');
        this.deleteEditor.on('change', function () {
            vm.workItem.deleteSql = vm.deleteEditor.getValue();
        });
        this.beans = this.getBeans();
        this.processBeans = this.getProcessBeans();
    },
    created: function () {

        if (id != null) {
            this.title = "修改";
            this.getInfo(id)
        } else {
            if (workId) {
                this.getDefault(workId);
            }
        }
    },
    methods: {
        createSub: function () {
            vm.workItemSub = {subType: subTypes[0].dictCode};
            var ids = jQuery("#subJqGrid").jqGrid('getDataIDs');
            //获得当前最大行号（数据编号）
            var rowid = Math.max.apply(Math, ids);
            //获得新添加行的行号（数据编号）
            newrowid = rowid + 1;

            layer.open({
                type: 1,
                offset: '200px',
                skin: 'layui-layer-lan',
                title: "添加子模块",
                area: ['800px', '600px'],
                shade: 0,
                shadeClose: false,
                content: jQuery("#subLayer"),
                btn: ['确定', '取消'],
                btn1: function (index) {
                    layer.close(index);
                    var dataRow = vm.workItemSub;
                    //将新添加的行插入到第一列
                    $("#subJqGrid").jqGrid("addRowData", newrowid, dataRow, "last");
                }
            });
        },
        updateRow: function (rowId) {
            if (rowId == null) {
                return;
            }

            var rowData = $("#subJqGrid").jqGrid('getRowData', rowId);
            vm.workItemSub = rowData;
            layer.open({
                type: 1,
                offset: '200px',
                skin: 'layui-layer-lan',
                title: "修改子模块",
                area: ['800px', '600px'],
                shade: 0,
                shadeClose: false,
                content: jQuery("#subLayer"),
                btn: ['确定', '取消'],
                btn1: function (index) {
                    layer.close(index);
                    var dataRow = vm.workItemSub;
                    //将新添加的行插入到第一列
                    $("#subJqGrid").jqGrid("setRowData", rowId, dataRow);
                }
            });
        },
        deleteSubRow: function (rowId) {
            if (rowId == null) {
                return;
            }
            $("#subJqGrid").jqGrid("delRowData", rowId);
        },
        handleEdit: function (index, row) {
            this.dialogFormVisibleForUpdate = true;
            this.form = Object.assign({}, row);
            this.table_index = index;
        },
        handleAdd: function (index, row) {
            this.dialogFormVisibleForAdd = true;
            this.form = Object.assign({}, row);
            this.form.dbKeyFrom = dbKeys[0].dictCode;
            this.form.subType = subTypes[0].dictCode;
            this.table_index = index;
        },
        handleDelete: function (index, row) {
            console.log(index, row);
        },
        handleDelete: function (index, row) {
            this.tableData.splice(index, 1);
            this.$message({
                message: "操作成功！",
                type: 'success'
            });
        },
        handleSaveForUpdate: function () {
            this.editLoading = true;
            this.tableData.splice(this.table_index, 1, this.form);
            this.editLoading = false;
            this.dialogFormVisibleForUpdate = false;
        },
        handleSaveForAdd: function () {
            this.editLoading = true;
            this.tableData.push(this.form);
            this.editLoading = false;
            this.dialogFormVisibleForAdd = false;
        },
        getInfo: function (id) {
            $.get("../workItem/info/" + id, function (r) {
                vm.workItem = r.workItem;

                if (vm.workItem.selectSql) {
                    vm.selectEditor.setValue(vm.workItem.selectSql);
                }
                if (vm.workItem.insertSql) {
                    vm.insertEditor.setValue(vm.workItem.insertSql);
                }
                if (vm.workItem.deleteSql) {
                    vm.deleteEditor.setValue(vm.workItem.deleteSql);
                }
                if (vm.workItem.dbKeyFrom) {
                    initTableNameAuto(vm.workItem.dbKeyFrom);
                }

                if (vm.workItem.dbKeyTo) {
                    initTableToAuto(vm.workItem.dbKeyTo);
                }
                if (vm.workItem.readerType) {
                    if ('0' == vm.workItem.readerType) {
                        $('#div_table').show();
                    } else {
                        $('#div_table').hide();
                    }
                }
            });
            $.get("../workItemSub/list/" + id, function (r) {
                vm.tableData = r.list;
            });
        },
        getBeans: function () {
            var url = "../workItem/getServiceBeans";
            var beans = null;
            $.ajax({
                type: "POST",
                url: url,
                async: false,
                success: function (r) {
                    beans = r.bean;
                }
            });
            return beans;
        },
        getProcessBeans: function () {
            var url = "../workItem/getProcessServiceBeans";
            var beans = null;
            $.ajax({
                type: "POST",
                url: url,
                async: false,
                success: function (r) {
                    beans = r.bean;
                }
            });
            return beans;
        },
        getMethodsByBeanName: function (beanName) {
            var url = "../workItem/getMethodsByBeanName";
            $.get(url, {beanName: beanName}, function (r) {
                vm.methods = r.methods;
                vm.workItem.methodName = r.methods[0].dictCode
            });
        },
        getDefault: function (workId) {
            var url = "../workItem/defaultValue";

            $.ajax({
                type: "POST",
                url: url,
                data: JSON.stringify({workId: workId}),
                success: function (r) {
                    if (r.defaultValue.execNum != null) {
                        vm.workItem.execNum = r.defaultValue.execNum;
                    }
                }
            });
        },
        saveOrUpdate: function (event) {
            //获取全部数据;
            vm.workItem.workItemSubs = getJQAllData("subJqGrid");
            var url = vm.workItem.id == null ? "../workItem/save" : "../workItem/update";
            $.ajax({
                type: "POST",
                url: url,
                data: JSON.stringify(vm.workItem),
                success: function (r) {
                    if (r.code === 0) {
                        alert('操作成功', function (index) {
                            vm.back();
                        });
                    } else {
                        alert(r.msg);
                    }
                }
            });
        },
        clickReaderType: function (event) {
            if ('0' == event.target.value) {
                $('#div_table').show();
            } else {
                $('#div_table').hide();
            }
        },
        createSelectSql: function () {
            $.ajax({
                type: "get",
                url: "../workDb/qrySelectSqlByTableName",
                data: {dbKey: vm.workItem.dbKeyFrom, qryName: vm.workItem.tableFrom},
                success: function (r) {
                    if (r.code === 0) {
                        vm.selectEditor.setValue(r.selectSql);
                        vm.workItem.selectSql = r.selectSql;
                    } else {
                        alert(r.msg);
                    }
                }
            });
        },
        createInsertSql: function () {
            $.ajax({
                type: "get",
                url: "../workDb/qryInsertSqlByTableName",
                data: {dbKey: vm.workItem.dbKeyTo, qryName: vm.workItem.tableTo},
                success: function (r) {
                    if (r.code === 0) {
                        vm.insertEditor.setValue(r.insertSql);
                        vm.workItem.insertSql = r.insertSql;
                    } else {
                        alert(r.msg);
                    }
                }
            });
        },
        back: function (event) {
            history.go(-1);
        },
        changeDbKeyFrom: function (event) {
            vm.workItem.tableFrom = '';
            initTableNameAuto(event.target.value);
        },
        changeDbKeyTo: function (event) {
            vm.workItem.tableTo = '';
            initTableToAuto(event.target.value);
        },
        changeSubType: function (event) {
            vm.workItemSub.subType = event.target.value;
        },
        changeCacheType: function (event) {
            if ("increment" == event.target.value) {
                vm.workItem.expireTime = 24 * 60 * 60 * 360 * 5;
            } else {
                vm.workItem.expireTime = 24 * 60 * 60;
            }
        },
        changeDetailMode: function (event) {
            var selectValue = event.target.value;
            detailModes.forEach(function (item) {
                if (selectValue == item.dictCode) {
                    vm.workItem.detailMode = item.dictCode;
                }
            });

        },
        changeBeanName: function (event) {
            var selectValue = event.target.value;
            vm.beans.forEach(function (item) {
                if (selectValue == item.dictCode) {

                    vm.workItem.beanName = item.dictCode;
                    vm.getMethodsByBeanName(item.dictName);
                }
            });
        },
        changeBeanMethod: function (event) {
            var selectValue = event.target.value;
            vm.methods.forEach(function (item) {
                if (selectValue == item.dictCode) {
                    vm.workItem.methodName = item.dictCode;
                }
            });
        },
    }
});
